package email

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"study/server/global"
	"study/server/model/request"
	resp "study/server/model/response"
	"study/server/utils/captcha"
	"study/server/utils/email"
	"study/server/utils/my_bind"
)

type EmailApi struct {
}

func (e *EmailApi) SendEmail(c *gin.Context) {
	emailReq, err := my_bind.MyBind[request.SendEmailReq](errors.New("请检查数据格式是否正确"), c)
	if err != nil {
		return
	}
	if !global.Config.Email.Verify() {
		resp.FailWithMsg("服务器邮箱配置错误,请联系管理员", c)
		return
	}
	// 校验验证码
	if global.Config.Captcha.Enable {
		// 校验验证码
		if emailReq.CaptchaID == "" || emailReq.CaptchaCode == "" {
			resp.FailWithMsg("验证码不能为空", c)
			return
		}
		// 校验验证码 -- 不管验证码是否正确,都删除验证码
		if !captcha.Store.Verify(emailReq.CaptchaID, emailReq.CaptchaCode, true) {
			resp.FailWithMsg("验证码错误", c)
			return
		}
	}

	id, _, answer, err := captcha.GenerateCaptcha()
	if err != nil {
		resp.FailWithMsg("验证码生成失败", c)
		return
	}
	email.Set(id, emailReq.Email, answer)

	err = email.SendEmail("用户注册", answer, emailReq.Email)
	if err != nil {
		logrus.Error("邮箱发送失败", err)
		resp.FailWithMsg("发送失败", c)
		return
	}
	resp.OkWithData(resp.SendEmailResp{
		EmailID: id,
	}, c)
}
